/*
 * To change this license header, choose License Headers in Project Properties.
 */

package dreamwar.view;

import dreamwar.controller.ArmyJpaController;
import dreamwar.controller.GUIController;
import dreamwar.model.MyEntityManagerFactory;
import dreamwar.model.POJO.Army;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Berto_Romero
 */
public class CreateArmyPanel extends javax.swing.JPanel {

    /**
     * Creates new form CreateArmyJPanel
     */
    public CreateArmyPanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        newArmyPropertiesPanel = new javax.swing.JPanel();
        armyNameLabel = new javax.swing.JLabel();
        armyNameTextField = new javax.swing.JTextField();
        continueAddingCheckBox = new javax.swing.JCheckBox();
        keypadPanel = new javax.swing.JPanel();
        acceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
        layout.columnWidths = new int[] {0};
        layout.rowHeights = new int[] {0, 7, 0};
        setLayout(layout);

        newArmyPropertiesPanel.setName(""); // NOI18N
        java.awt.GridBagLayout jPanel2Layout = new java.awt.GridBagLayout();
        jPanel2Layout.columnWidths = new int[] {0, 5, 0};
        jPanel2Layout.rowHeights = new int[] {0, 5, 0};
        newArmyPropertiesPanel.setLayout(jPanel2Layout);

        armyNameLabel.setText("Nombre");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        newArmyPropertiesPanel.add(armyNameLabel, gridBagConstraints);

        armyNameTextField.setPreferredSize(new java.awt.Dimension(200, 20));
        armyNameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                armyNameTextFieldActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        newArmyPropertiesPanel.add(armyNameTextField, gridBagConstraints);

        continueAddingCheckBox.setText("Aceptar y Seguir Introduciendo");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        newArmyPropertiesPanel.add(continueAddingCheckBox, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(25, 25, 0, 25);
        add(newArmyPropertiesPanel, gridBagConstraints);

        java.awt.GridBagLayout jPanel1Layout = new java.awt.GridBagLayout();
        jPanel1Layout.columnWidths = new int[] {0, 5, 0};
        jPanel1Layout.rowHeights = new int[] {0};
        keypadPanel.setLayout(jPanel1Layout);

        acceptButton.setText("Aceptar");
        acceptButton.setMaximumSize(new java.awt.Dimension(75, 23));
        acceptButton.setMinimumSize(new java.awt.Dimension(75, 23));
        acceptButton.setPreferredSize(new java.awt.Dimension(75, 23));
        acceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        keypadPanel.add(acceptButton, gridBagConstraints);

        cancelButton.setText("Volver");
        cancelButton.setMaximumSize(new java.awt.Dimension(75, 23));
        cancelButton.setMinimumSize(new java.awt.Dimension(75, 23));
        cancelButton.setPreferredSize(new java.awt.Dimension(75, 23));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        keypadPanel.add(cancelButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 25, 0);
        add(keypadPanel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void acceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptButtonActionPerformed
        createArmy();
    }//GEN-LAST:event_acceptButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        GUIController.getInstance().changeMainFrameCard(GUIController.ARMY_LIST_PANEL);
        clearFields();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void armyNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_armyNameTextFieldActionPerformed
        createArmy();
    }//GEN-LAST:event_armyNameTextFieldActionPerformed

    private void createArmy() {
        String newName = armyNameTextField.getText().trim();
        clearFields();
        if (!newName.isEmpty()) {
            boolean isLastIndex = true;
            ArmyJpaController armyJpaController = new ArmyJpaController(MyEntityManagerFactory.getInstance().getEntityManagerFactory());
            int idArmy = generateArmyId(armyJpaController);
            Army army = new Army(idArmy);
            army.setArmyName(newName);
            try {
                armyJpaController.create(army);
                isLastIndex = (idArmy == armyJpaController.getArmyCount());
                if (isLastIndex) GUIController.getInstance().createArmy(army); else GUIController.getInstance().createArmy(idArmy - 1 ,army);
            } catch (Exception ex) {
                Logger.getLogger(CreateArmyPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (!continueAddingCheckBox.isSelected()) {
            GUIController.getInstance().changeMainFrameCard(GUIController.ARMY_LIST_PANEL);
            clearFields();
        }
    }
    
    private int generateArmyId(ArmyJpaController armyJpaController) {
        List<Army> armyList = armyJpaController.findArmyEntities();
        if (armyList == null) armyList = Collections.emptyList();
        int totalEntries = armyJpaController.getArmyCount();
        if (armyList.get(totalEntries - 1).getIdArmy() != totalEntries) {
            for (int i = 0; i < armyList.size(); i++) {
                Army army = armyList.get(i);
                if (army.getIdArmy() != (i + 1)) {
                    return (i + 1);
                }
            }
        }
        return totalEntries + 1;
    }
    
    private void clearFields() {
        armyNameTextField.setText("");
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JLabel armyNameLabel;
    private javax.swing.JTextField armyNameTextField;
    private javax.swing.JButton cancelButton;
    private javax.swing.JCheckBox continueAddingCheckBox;
    private javax.swing.JPanel keypadPanel;
    private javax.swing.JPanel newArmyPropertiesPanel;
    // End of variables declaration//GEN-END:variables
}
